package com.example.androidservicetutorial;

import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.example.androidservicetutorial.service.ProgressService;

public class ProgressServiceActivity extends AppCompatActivity {
    private ProgressService progressService;
    private int progress = 0;
    private ProgressBar progressBar;
    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            progressService = ((ProgressService.ProgressBinder)service).getService();
            progressService.setOnProgressListener(new ProgressService.OnProgressListener() {
                @Override
                public void onProgress(int progress) {
                    progressBar.setProgress(progress);
                }
            });
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_progress_service);

        Intent intent = new Intent(this,ProgressService.class);
        bindService(intent,connection, Service.BIND_AUTO_CREATE);

        progressBar = findViewById(R.id.progressBar);
        final Button btnDownload = findViewById(R.id.btnDownload);
        btnDownload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                progressService.startDownload();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(connection);
    }
}
